package com.cango.student.io.file;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileNio {

    public static void main(String[] args) {
        try {
//            fileNio();
            copyfileNio();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件内容
     * @throws Exception
     */
    public static void fileNio() throws Exception {
        RandomAccessFile aFile  = new RandomAccessFile("d:\\1.txt", "rw");
        FileChannel fileChannel = aFile.getChannel();
        //分配缓存区大小
        ByteBuffer buf = ByteBuffer.allocate(48);

        int bytesRead = fileChannel.read(buf);
        while (bytesRead != -1) {
//            System.out.println("Read " + bytesRead);
            // buf.flip()的调用，首先读取数据到Buffer,position+1，然后反转Buffer,接着再从Buffer中读取数据
            // 需要调用flip方法，将position设置为0，limit设置为以前的position的位置
            // （注：flip：空翻，反转）
            buf.flip();
            //判断是否有剩余（注：Remaining：剩余的）
            byte[] bytes = new byte[bytesRead];
            int i = 0;
            while (buf.hasRemaining()) {
//                System.out.print((char) buf.get());
                bytes[i]= buf.get();
                i++;
            }
            System.out.print(new String(bytes));
            buf.clear();
            bytesRead = fileChannel.read(buf);
        }
        aFile.close();
    }

    /**
     * 读取文件内容
     * @throws Exception
     */
    public static void copyfileNio() throws Exception {
        RandomAccessFile aFile = new RandomAccessFile("d:\\1.txt", "rw");
        RandomAccessFile tFile = new RandomAccessFile("d:\\erp-sms-web.log", "rw");
        FileChannel fileChannel = aFile.getChannel();
        FileChannel toChannel = tFile.getChannel();
        //分配缓存区大小
        ByteBuffer buf = ByteBuffer.allocateDirect(48);
        int bytesRead = fileChannel.read(buf);
        while (bytesRead != -1) {
//            System.out.println("Read " + bytesRead);
            // buf.flip()的调用，首先读取数据到Buffer,position+1，然后反转Buffer,接着再从Buffer中读取数据
            // 需要调用flip方法，将position设置为0，limit设置为以前的position的位置
            // （注：flip：空翻，反转）
            buf.flip();

            toChannel.write(buf);
            buf.clear();
            bytesRead = fileChannel.read(buf);
        }
        aFile.close();
    }

    /**
     * transferTo拷贝
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copyFileByChannel(File source, File dest) throws
            IOException {
        try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
             FileChannel targetChannel = new FileOutputStream(dest).getChannel()) {
            for (long count = sourceChannel.size(); count > 0; ) {
                long transferred = sourceChannel.transferTo(
                        sourceChannel.position(), count, targetChannel);
                sourceChannel.position(sourceChannel.position() + transferred);
                count -= transferred;
            }
        }
    }
}
